package com.unitd.frame.comm.serializer.impl;

import com.unitd.frame.comm.serializer.ISerializer;

import java.io.*;

/**
 * @desc JDK标准实现序列化
 * @filename JavaSerializer.java
 * @copyright www.unitd.com
 * @author Hudan
 * @version 1.0
 * @date 2017/02/18
 */
public class JavaSerializer implements ISerializer {

	/**
	 * @desc 获取序列化类型名称
	 * @return
	 */
	@Override
	public String name() {
		return "java";
	}

	/**
	 * @desc 序列化指定对象
	 * @param obj 需要序列化的对象
	 * @return
	 * @throws IOException
	 */
	@Override
	public byte[] serialize(Object obj) throws IOException {
		ObjectOutputStream oos = null;
		try {
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			oos = new ObjectOutputStream(baos);
			oos.writeObject(obj);
			return baos.toByteArray();
		} finally {
			if (oos != null)
				try {
					oos.close();
				} catch (IOException e) {
				}
		}
	}

	/**
	 * @desc 反序列化指定对象
	 * @param bytes 需要反序列化的对象
	 * @return
	 * @throws IOException
	 */
	@Override
	public Object deserialize(byte[] bytes) throws IOException {
		if (bytes == null || bytes.length == 0)
			return null;
		ObjectInputStream ois = null;
		try {
			ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
			ois = new ObjectInputStream(bais);
			return ois.readObject();
		} catch (ClassNotFoundException e) {
			throw new RuntimeException(e);
		} finally {
			if (ois != null)
				try {
					ois.close();
				} catch (IOException e) {
				}
		}
	}
}